<?php

namespace App\Http\Middleware;

use App\Services\IpBlacklistService;
use Closure;
use Illuminate\Http\Request;

class CheckIpBlacklist
{
    protected $ipBlacklistService;
    protected $exceptRoutes;

    public function __construct(IpBlacklistService $ipBlacklistService)
    {
        $this->ipBlacklistService = $ipBlacklistService;
        $this->exceptRoutes = config('ip_blacklist.except_routes', []);
    }

    public function handle(Request $request, Closure $next)
    {
        $ip = $request->ip();
        
        // 检查是否在排除列表中
        if ($this->shouldPassThrough($request)) {
            // 记录访问日志（但不检查黑名单）
            $this->ipBlacklistService->logAccess($ip, $request->path(), 'excluded_route');
            return $next($request);
        }

        // 记录访问日志
        $this->ipBlacklistService->logAccess($ip, $request->path());
        
        // 检查是否在黑名单中
        if ($this->ipBlacklistService->isBlacklisted($ip)) {
            return response()->json([
                'error' => 'Access denied - IP is blacklisted',
                'ip' => $ip
            ], 403);
        }

        return $next($request);
    }

    /**
     * 检查请求是否应该跳过黑名单检查
     */
    protected function shouldPassThrough($request)
    {
        foreach ($this->exceptRoutes as $route) {
            if ($request->is($route)) {
                return true;
            }
        }

        return false;
    }
}
